import * as spritejs from 'spritejs'
import { Car } from './Car'
const { Scene, Sprite, Polyline, Rect, Label } = spritejs

export const parkSpacesList: ParkSpace[] = []

/**
 * 停车位类
 */
export class ParkSpace {
    id
    options
    rect
    layer
    x
    y
    text
    constructor(id: string, layer: any, options: any) {
        this.id = id
        this.options = options
        this.layer = layer
        this.x = options.x === undefined ? 500 : options.x
        this.y = options.y === undefined ? 500 : options.y
        this.rect = new Rect({
            id: id,
            anchor: [0.5, 0.5],
            size: [100, 200],
            pos: [this.x, this.y],
            strokeColor: '#eee',
            lineDash: [5, 5],
            strokeWidth: 1,
        })
        this.text = new Label({
            pos: [this.x + 20, this.y + 20],
            text: this.id,
            font: '18px Arial',
            fillColor: '#eee',
            anchor: [0.5, 0.5],
        })
        this.init()
        parkSpacesList.push(this)
    }

    init() {
        this.layer.append(this.rect)
        this.layer.append(this.text)
    }

    remove() {
        this.rect.remove()
        this.text.remove()
        const index = parkSpacesList.findIndex((item) => item.id === this.id)
        if (index !== -1) {
            parkSpacesList.splice(index, 1)
        }
    }
}

export const drawParkSpaces = (list: any[], layer: any) => {
    // 画之前清空
    parkSpacesList.forEach((item) => item.remove())
    let n = list.length
    let m = n / 3
    let i = 0
    for (let j = 0; j < m; j++) {
        for (let k = 0; k < 5 && i < n; k++) {
            const item = list[i]
            const x = 310 + k * 100 + k * 95
            const y = 250 + j * 200 + j * 100
            const parkSpace = new ParkSpace(`${item.number}`, layer, {
                x,
                y,
                parkSpaceInfo: item,
            })
            if (item.status === 1) {
                // 已经有车停在这里了
                new Car(layer, 'unknown', {
                    clickable: false,
                    x: x + 50,
                    y: y + 100,
                    parkSpaceId: item.number,
                })
                parkSpace.rect.attr('strokeColor', '#409eff')
            }
            i++
        }
    }
}
